package io.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseDecoder;
import io.netty.util.internal.shaded.org.jctools.queues.MessagePassingQueue.Consumer;

/**
 * 搭建一个Netty服务器：HttpServer
 * 参考：https://www.jianshu.com/p/ed0177a9b2e3
 * @author ben
 * @date 2021-11-01 21:47:48 CST
 */
public class HttpServer1 {

	private static Consumer<Object> cs = System.out::println;
	
	private final int port;
	
	public HttpServer1(int port) {
		this.port = port;
	}
	
	// 启动服务器
	public void start() throws Exception {
		ServerBootstrap sb = new ServerBootstrap();
		NioEventLoopGroup group = new NioEventLoopGroup();
		
		sb.group(group)
			.channel(NioServerSocketChannel.class)
			.childHandler(new ChannelInitializer<SocketChannel>() {

				@Override
				protected void initChannel(SocketChannel ch) throws Exception {
					cs.accept("initChannel ch: " + ch);
					ch.pipeline()
						.addLast("decoder", new HttpRequestDecoder())
						.addLast("encoder", new HttpResponseDecoder())
						.addLast("aggregator", new HttpObjectAggregator(512 * 1024))
						.addLast("handler", new HttpHandler1());
				}
				
			})
			.option(ChannelOption.SO_BACKLOG, 128)
			.childOption(ChannelOption.SO_KEEPALIVE, Boolean.TRUE);
		
		
		cs.accept("启动服务器...2");
		sb.bind(port).sync();
		cs.accept("启动服务器...3");
	}
	
	public static void main(String[] args) throws Exception {
		final int port = 10000;
		
		cs.accept("启动服务器...1");
		new HttpServer1(port).start();
	}

}
